import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)

import routes from './routes'

let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(this, location, () => { }, () => { });
    }
}

VueRouter.prototype.replace = function (location, replace, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject);
    } else {
        originReplace.call(this, location, () => { }, () => { });
    }
}

const router = new VueRouter({
    routes,
    // 滚动行为
    scrollBehavior(to, from, savedPosition) {
        // 始终滚动到顶部
        return { y: 0 }
    },
})

router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token;
    let username = store.state.user.userInfo.name;
    let toPath = to.path;
    if (token) {
        // 已登录
        if (to.path == '/login') {
            next('/')
        } else {
            if (!username) {
                try {
                    await store.dispatch("getUserInfo")
                    next();
                } catch (error) {
                    // token过期
                    await store.dispatch('logout')
                    next('/login');
                }
            } else {
                next()
            }
        }
    } else {
        // 未登陆
        if (toPath.indexOf('/center') != -1 || toPath.indexOf('/pay') != -1 || toPath.indexOf('/trade') != -1) {
            next('/login?redirect=' + toPath)
        } else {
            next()
        }
    }
})

export default router;